var express = require('express');
var router = express.Router();
//引入mysql
const mysql = require('mysql')

let connObj = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  port: '3306',
  database: 'stu'
})
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express123' });
});

router.get('/login', function (req, res, next) {
  res.render('login', { title: 'Express123' });
});

router.get('/register', function (req, res, next) {
  res.render('register', { title: 'Express123' });
});

router.post('/login', function (req, res, next) {
  let { tel, pass } = req.body
  let sql1 = `select * from user where username = '${tel}' ;`
  connObj.query(sql1, (err, results) => {
    if (results[0] == undefined) {
      res.send('用户名不存在')
      return
    }
    if (results[0].password !== pass) {
      res.send('用户名密码不匹配')
      return
    } else {
      res.render('users', { results });
    }

  })
});
router.post('/register', function (req, res, next) {
  let { username, password, repwd } = req.body
  username = username.trim()
  password = password.trim()
  repwd = repwd.trim()
  //2. 必须做一些数据验证
  //2.1 是否为空
  if (username == '' || !password || !repwd) {
    res.send('请传递必要参数')
    return //都已经send响应结果了，没必要再往下执行
  }
  //2. 格式判断： 长度
  //用户名不到小于5位 不能大于 15位
  if (username.length < 5 || username.length > 15) {
    res.send('用户名不到小于5位 不能大于 15位')
    return
  }
  //两次密码不一致
  if (password != repwd) {
    res.send('两次密码不一致')
    return
  }

  let sql0 = `select * from user where username = '${username}' ;`
  connObj.query(sql0, (err, results) => {
    if (results[0] !== undefined) {
      res.send('用户名已存在')
      return
    }
  })

  let time = Date.now()
  let sql1 = `INSERT INTO user ( username,password,time ) VALUES ( '${username}','${password}','${time}' )`
  connObj.query(sql1, (err, results) => {
    if (results.affectedRows !== 1) {
      res.send('注册失败')
      return
    }
    let sql2 = `select * from user;`
    connObj.query(sql2, (err, results) => {
      res.render('users', { results });
    })

  })
});



module.exports = router;
